<template>
  <HuilanBasic :left-width="280">
    <template v-slot:left>
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree placeholder="" ref="menuTree" :option="treeOption" node-key="id" :data="treeData"
              @node-click="nodeClick" :before-open="beforeOpen">
              <template slot-scope="{ node, data }">
                <span class="custom-tree-node">
                  <span :class="{ text: true, textActive: nodeKey === data.id }">{{ node.label }}</span>
                  <span v-if="nodeKey === data.id">
                    <i class="el-icon-edit" @click="edit(data)"></i>
                    <i class="el-icon-delete el-icon-delete-sty" @click="dele(data.id)"></i>
                  </span>
                </span>
              </template>
              <template slot="addBtn">
                <!-- <el-button type="primary" size="mini" @click="add">添加</el-button> -->
                <i @click="add" class="el-icon-plus el-icon-plus-btn"></i>
              </template>
            </avue-tree>
          </basic-container>
        </el-scrollbar>
      </div>
    </template>
    <QSGDrawer :title="dataInTitle" :fullscreen="false" :size="600" append-to-body
      :visible.sync="intelligentClassificationVisible" :wrapperClosable="false" :before-close="beforeClose">
      <avue-form :option="option" ref="form" v-model="form" :upload-preview="uploadPreview" @submit="submit">
      </avue-form>
      <template v-slot:footer>
        <el-button size="small" type="primary" :loading="saveLoading" @click.stop="formSave">确 定</el-button>
        <el-button size="small" @click.stop="formClose">取 消</el-button>
      </template>
    </QSGDrawer>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="模型介绍" name="modelIntroduction">
        <ModelIntroduction ref="modelIntroduction"></ModelIntroduction>
      </el-tab-pane>
      <el-tab-pane label="分类管理" name="classificationMg">
        <ClassificationMg v-if="activeName === 'classificationMg'" ref="classificationMgRef"></ClassificationMg>
      </el-tab-pane>
      <el-tab-pane label="模型训练" name="modelTraining">
        <TrainingRecords ref="modelTrainingRef"></TrainingRecords>
      </el-tab-pane>
    </el-tabs>
  </HuilanBasic>
</template>

<script>
import QSGDrawer from "@/components/QSGDrawer/index";
import ModelIntroduction from "./modelIntroduction";
import ClassificationMg from "./classificationMg";
import TrainingRecords from "./trainingRecords";
import { save, list, detail, deleteTree, update } from "@/api/configure/intelligentClassification";

export default {
  name: "intelligentClassification",
  components: {
    QSGDrawer,
    ModelIntroduction,
    ClassificationMg,
    TrainingRecords
  },
  data() {
    return {
      dataInTitle: '智能分类',
      intelligentClassificationVisible: false,
      activeName: 'modelIntroduction',
      classifyId: '',
      nodeKey: '',
      saveLoading: false,
      treeData: [
      ],
      option: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 90,
        updateBtnIcon: ' ',
        cancelBtnIcon: ' ',
        saveBtnIcon: ' ',
        addBtnIcon: ' ',
        column: [
          {
            label: '分类名称',
            prop: "name",
            span: 24,
            showText: true,
            maxlength: 20,
            showWordLimit: true,
            clearable: true,
            rules: [
              {
                required: true,
                message: '请输入分类名称',
                trigger: "blur",
              },
              {
                min: 1,
                max: 20,
                message: "长度在 1 到 20 个字符",
                trigger: "blur",
              },
            ],
          },
          {
            label: '分类描述',
            prop: "introduce",
            type: 'textarea',
            row: 3,
            span: 24,
            maxlength: 100,
            clearable: true,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message: '请输入分类描述',
                trigger: "blur",
              },
              {
                min: 1,
                max: 100,
                message: "长度在 1 到 100 个字符",
                trigger: "blur",
              },
            ],
          },
        ]
      },
      treeOption: {
        addBtn: false,
        editBtn: false,
        delBtn: false,
        defaultExpandAll: true,
      }
    };
  },

  watch: {

  },
  computed: {

  },
  created() {
  },
  mounted() {
    this.treeList()
  },
  methods: {
    beforeOpen(type) {
      console.log(type)
    },
    add() {
      const self = this
      this.title = '新增'
      this.intelligentClassificationVisible = true
      setTimeout(() => {
        self.$refs.form.resetForm()
      }, 500);

    },
    formSave() {
      this.$refs.form.submit()
    },
    submit(data, done) {
      if (this.title === '新增') {
        this.saveLoading = true
        save(data).then(res => {
          if (res.data.success) {
            this.$message.success('保存成功')
            this.intelligentClassificationVisible = false
            this.treeList()
          }
          this.saveLoading = false
          done()
        }).catch(() => {
          this.saveLoading = false
          done()
        })
      } else {
        const params = {
          id: this.nodeKey,
          ...data
        }
        update(params).then(res => {
          if (res.data.success) {
            this.$message.success('保存成功')
            this.intelligentClassificationVisible = false
            this.treeList()
          }
          done()
        })
      }
    },
    formClose() {
      this.$refs.form.resetForm()
      this.intelligentClassificationVisible = false
    },
    beforeClose() {
      // this.$refs.form.resetForm()
      this.formClose()
    },
    treeList() {
      const self = this
      list({}).then(res => {
        const data = res.data.data
        data.map(item => {
          item.label = item.name
          item.id = item.id
        })
        this.treeData = data || []
        setTimeout(() => {
          var nodes = document.querySelectorAll('.el-tree-node');
          if (nodes && nodes[0]) {
            // 模拟点击事件来展开第一个节点
            var event = new MouseEvent('click', { bubbles: true });
            nodes[0].dispatchEvent(event);
            self.defaultFirst(data[0].id)
          } else {
            console.log("未找到任何节点");
          }
        }, 500)
      })
    },
    nodeClick(val) {
      this.nodeKey = val.id
      this.classifyId = val.id
      switch (this.activeName) {
        case 'modelIntroduction':
          this.detailData(val.id)
          this.$refs.modelIntroduction.init(val.id)
          break;
        case 'classificationMg':
          this.$refs.classificationMgRef.init(val.id)
          break;
        case 'modelTraining':
          this.$refs.modelTrainingRef.init(val.id)
          break;
      }
    },
    detailData(id) {
      const self = this
      const data = {
        id
      }
      detail(data).then(res => {
        if (res.data.success) {
          self.$refs.modelIntroduction.setModelValue(res.data.data)
        }
      })
    },
    edit(row) {
      this.intelligentClassificationVisible = true
      const self = this
      setTimeout(() => {
        self.form.name = row.name
        self.form.introduce = row.introduce
      }, 500)
      this.title = '编辑'
    },
    dele(ids) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTree({ ids }).then(res => {
          if (res.data.success) {
            this.$message.success('删除成功')
            this.treeList()
          }
        })
      }).catch(() => {

      });
    },
    handleClick(val) {
      if (val.index === '1') {
        this.$nextTick(() => {
          this.$refs.classificationMgRef.init(this.classifyId)
        })
      } else if (val.index === '2') {
        this.$refs.modelTrainingRef.init(this.classifyId)
      } else if (val.index === '0') {
        this.detailData(this.classifyId)
        this.$refs.modelIntroduction.init(this.classifyId)
      }
    },
    defaultFirst(classifyId) {
      this.$refs.modelIntroduction.init(classifyId)
    }
  },
};
</script>

<style scope lang="scss">
.custom-tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.text {
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-icon-delete-sty {
  flex: 1 1 0%;
  margin-left: 10px;
  margin-right: 5px;
}

.textActive {
  color: #0045c8;
}

.el-icon-plus-btn {
  color: #0045c8;
  cursor: pointer;
  font-size: 20px;
  font-weight: bold;
}
</style>
